from sqlalchemy.orm import sessionmaker
from application.config.mysql import engine, async_engine
from sqlalchemy.orm import declarative_base

# 创建数据库会话工厂
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)


# 通过依赖注入获取数据库会话的函数
def get_db():
    db = SessionLocal()
    try:
        yield db
    except:
        db.rollback()  # 发生异常时回滚事务
        raise
    finally:
        db.close()


# ----------------------------------------异步-------------------------------------
from sqlalchemy.ext.asyncio import AsyncSession

async_session = AsyncSession(async_engine)
Base = declarative_base()


async def get_asyncdb():
    async with async_session() as session:
        yield session